const express = require('express');
const WebSocket = require('ws');
const http = require('http');
const roomController = require('./controllers/roomController');
// const { setupWebSocket } = require('./websocket/connection');
const roomService = require('./services/roomService');
const UnifiedHandler = require('./websocket/UnifiedHandler');
// const { handleMessage } = require('./websocket/handler');
// const RoomHandler = require('./websocket/roomHandler');
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });

// 创建房间处理器实例
const unifiedhandler = new UnifiedHandler(wss);
// const roomHandler = new RoomHandler(wss);

// 添加跨域支持
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
  next();
});

// REST API路由
app.use(express.json());
app.use('/api/room', roomController);

// WebSocket连接处理
wss.on('connection', (ws) => {
  unifiedhandler.handleConnection(ws);
});

// 设置定时清理任务
setInterval(() => {
  roomService.cleanExpiredRooms();
}, 60 * 1440 * 1000); // 每天执行一次，60 秒 * 60 分钟 * 24 * 1000 毫秒/秒 = 86,400,000 毫秒 = 24 小时

// 启动服务器
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
  console.log(`服务器运行在端口 ${PORT}`);
}); 